package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApReadBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.exception.CustomException;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class ApReadBehaviorServiceimpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior> implements ApReadBehaviorService {
    @Resource
    ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //参数校验
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //获取登录用户
        ApUser user = AppThreadLocalUtils.getUser();

        //查询行为实体是否存在
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());

        if (apBehaviorEntry == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApReadBehavior readBehavior = this.getOne(Wrappers.<ApReadBehavior>lambdaQuery().eq(ApReadBehavior::getEntryId, apBehaviorEntry.getEntryId()).eq(ApReadBehavior::getArticleId, dto.getArticleId()));

        if (readBehavior == null) {

            //封装保存数据
            ApReadBehavior apReadBehavior = new ApReadBehavior();
            apReadBehavior.setArticleId(dto.getArticleId());
            apReadBehavior.setCount(dto.getCount());
            apReadBehavior.setCreatedTime(new Date());
            apReadBehavior.setEntryId(apBehaviorEntry.getId());
            apReadBehavior.setLoadDuration(dto.getLoadDuration());
            apReadBehavior.setPercentage(dto.getPercentage());
            apReadBehavior.setReadDuration(dto.getReadDuration());

            //保存
            this.save(apReadBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else {  //修改
            readBehavior.setCount((short) (readBehavior.getCount() + 1));

            readBehavior.setUpdatedTime(new Date());

            this.updateById(readBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }


    }
}
